﻿using System;

namespace CamlQueryCreator.Common
{
    /// <summary>
    /// Соединяющий элемент ("И", "ИЛИ") CAML-запроса.
    /// </summary>
    public abstract class CamlConnectorAndOr : CamlConnector
    {
        private const string QUERY_FORMAT = "<{2}>{0}{1}</{2}>";

        protected abstract string ConnectorHeader { get; }

        private readonly Func<ICamlConnector, CamlElement> _getOperator1;
        private readonly Func<ICamlConnector, CamlElement> _getOperator2;

        /// <summary>
        /// Соединяющий элемент ("И", "ИЛИ") CAML-запроса.
        /// <para>Конструктор.</para>
        /// </summary>
        protected CamlConnectorAndOr(CamlConnector parentBuilder, Func<ICamlConnector, CamlElement> getOperator1, Func<ICamlConnector, CamlElement> getOperator2)
            : base(parentBuilder)
        {
            _getOperator1 = getOperator1;
            _getOperator2 = getOperator2;
        }

        #region Overrides of CamlBase

        /// <summary>
        /// Формирует запрос на основе итогового дочернего запроса и возвращает результат.
        /// </summary>
        protected sealed override string GetQuery(string childQuery)
        {
            var query1 = _getOperator1(this).GetQuery();
            var query2 = _getOperator2(this).GetQuery();

            if (string.IsNullOrEmpty(query1))            
                return query2;

            if (string.IsNullOrEmpty(query2))
                return query1;

            return string.Format(QUERY_FORMAT,
                                 query1,
                                 query2,
                                 ConnectorHeader);
        }

        #endregion
    }
}
